import 'dart:async';

import 'package:flutter/material.dart';
import 'package:bloc/bloc.dart';

typedef StateBuilder<T> = Widget Function(T state);

class SimpleBlocProvider<T> extends StatefulWidget {
  final StateBuilder<T> builder;
  final BlocBase<T> bloc;
  const SimpleBlocProvider(
      {Key? key, required this.builder, required this.bloc})
      : super(key: key);

  @override
  _SimpleBlocProviderState<T> createState() => _SimpleBlocProviderState<T>();
}

class _SimpleBlocProviderState<T> extends State<SimpleBlocProvider<T>> {
  late T _state;
  late StreamSubscription<T> _streamSubscription;

  @override
  void initState() {
    _state = widget.bloc.state;
    super.initState();
    _streamSubscription = widget.bloc.stream.listen((data) {
      setState(() {
        _state = data;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return widget.builder(_state);
  }

  @override
  void dispose() {
    _streamSubscription.cancel();
    super.dispose();
  }
}
